<?php

namespace app\common\model\presalesCustomer;

use cores\BaseModel;
use think\model\relation\BelongsTo;

class PresalesCustomer extends BaseModel
{
// 定义表名
    protected $name = 'presales_customer';

    // 定义主键
    protected $pk = 'pc_id';

    protected $append = [
        'follow_up_count',
        'last_follow_up_info',
        'next_log_time_text',
        'last_log_time_text',
        'log_status',
    ];

    /**
     * 跟进次数
     */
    public function getFollowUpCountAttr($value, $data)
    {
        return (new Log())->where(['pc_id' => $data['pc_id'], 'is_delete' => 0])->count();
    }

    /**
     * 最后跟进信息
     */
    public function getLastFollowUpInfoAttr($value, $data)
    {
        return (new Log())->where(['pc_id' => $data['pc_id'], 'is_delete' => 0])->order('pcl_id', 'desc')->find();
    }

    public function getNextLogTimeTextAttr($value, $data)
    {
        return !empty($data['next_log_time']) ? date("Y-m-d H:i:s", $data['next_log_time']) : '';
    }

    public function getLastLogTimeTextAttr($value, $data)
    {
        return !empty($data['last_log_time']) ? date("Y-m-d H:i:s", $data['last_log_time']) : '';
    }

    public function getLogStatusAttr($value, $data)
    {
        if (!empty($data['next_log_time'])) {
            if (time() > $data['next_log_time']) {
                //已逾期
                return 2;
            }elseif (date("Y-m-d", $data['next_log_time']) == date("Y-m-d", time())) {
                //今日待处理
                return 1;
            } else {
                //无需处理
                return 0;
            }
        } else {
            //无需处理
            return 0;
        }
    }

    /**
     * 关联用户记录表
     * @return BelongsTo
     */
    public function storeUser(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\store\\User", 'store_user_id');
    }

    /**
     * 关联来源记录表
     * @return BelongsTo
     */
    public function source(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\presalesCustomer\\Source", 'pcs_id');
    }

    /**
     * 关联用户记录表
     * @return BelongsTo
     */
    public function type(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\presalesCustomer\\Type", 'pct_id');
    }
}
